<template>
  <div class="login-container">
    <div class="login-wrapper">
      <!-- 左侧介绍区域（仅在大屏幕显示） -->
      <div class="login-intro" :class="{ 'hidden': isMobile }">
        <div class="intro-content">
          <h1>欢迎来到二手交易市场</h1>
          <p>在这里您可以轻松买卖各类二手商品，环保又实惠</p>
          <div class="features">
            <div class="feature-item">
              <i class="el-icon-check"></i>
              <span>安全可靠的交易平台</span>
            </div>
            <div class="feature-item">
              <i class="el-icon-check"></i>
              <span>便捷的商品发布流程</span>
            </div>
            <div class="feature-item">
              <i class="el-icon-check"></i>
              <span>实时聊天沟通</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 登录表单区域 -->
      <div class="login-box">
        <div class="login-header">
          <h1 class="title">{{ isMobile ? '登录' : '欢迎回来' }}</h1>
          <p class="subtitle">{{ isMobile ? '请输入账号信息' : '请输入您的账号信息' }}</p>
        </div>
        
        <el-form 
          ref="loginFormRef" 
          :model="loginForm" 
          :rules="loginRules" 
          class="login-form"
          @keyup.enter="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="UserFilled"
              size="large"
              clearable
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Key"
              size="large"
              show-password
            />
          </el-form-item>

          <el-form-item prop="captcha" class="captcha-form-item">
            <div class="captcha-wrapper">
              <el-input
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
                prefix-icon="Picture"
                size="large"
                class="captcha-input"
              />
              <div class="captcha-image" @click="refreshCaptchaCode">
                <img :src="captchaImage" alt="验证码" v-if="captchaImage">
                <div class="loading-captcha" v-else>{{ captchaImageTip }}</div>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item class="form-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <a href="#" class="forgot-password">忘记密码？</a>
          </el-form-item>
          <!-- <p @click="getpiniamenus">test</p> -->
          
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-button"
              :loading="loading"
              @click="handleLogin"
              block
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="login-footer">
          <p>还没有账号？<router-link to="/register">立即注册</router-link></p>
          <div class="other-login">
            <span>其他登录方式：</span>
            <i class="el-icon-platform-eleme other-icon"></i>
            <i class="el-icon-wechat other-icon"></i>
            <i class="el-icon-github other-icon"></i>
          </div>
        </div>
      </div>
    </div>
    
    <div class="background-decoration">
      <div class="circle circle-1"></div>
      <div class="circle circle-2"></div>
      <div class="circle circle-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import deviceDetector from '@/utils/deviceDetector'
import { refreshCaptcha,login } from '@/api/common/login'
import {HttpStatus} from '@/utils/enum/HttpStatus'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'vue-router'
import {sortChildren} from "@/utils/menu"

// 表单引用
const loginFormRef = ref(null)

// 响应式数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, validator: validateCaptcha, trigger: 'blur' }
  ]
}

const loading = ref(false)
const rememberMe = ref(true)
const isMobile = ref(false)
const captchaImage = ref('')
const captchaImageTip = ref('加载中...')

// 验证码自定义验证规则
function validateCaptcha(rule, value, callback) {
  if (!value) {
    callback(new Error('请输入验证码'))
  } else if (value.length > 4) {
    callback(new Error('验证码长度不在指定范围'))
  } else {
    callback()
  }
}

// 刷新验证码
const refreshCaptchaCode = async () => {
  try {
    const response = await refreshCaptcha()
    captchaImage.value = 'data:image/png;base64,'+response.data
  } catch (error) {
    captchaImageTip.value = "加载异常 (>。<)"
    console.log(error);
    
  }
}

// 处理设备状态变化
const handleDeviceChange = (mobile) => {
  isMobile.value = mobile
}

// 获取用户存储
const userStore = useUserStore()
// 获取路由
const router = useRouter()
// 处理登录
const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      login({
        username: loginForm.username,
        password: loginForm.password,
        captcha: loginForm.captcha,
      }).then((response) => { 
        loading.value = false
        if (response.code === HttpStatus.WARN) { 
          refreshCaptchaCode()
          return false;
        }
        userStore.setLoginData({
          roles: response.roles,
          user: response.user,
          token: response.token
        })
        
        const routerList = response.routerList
        sortChildren(routerList)
        userStore.setMenuData(routerList)
        router.push('/store')

      })
    } else {
      // 验证失败时刷新验证码
      refreshCaptchaCode()
      return false
    }
  })
}

const getpiniamenus=()=>{ 
  console.log(userStore.getMenus)
}


// 组件挂载时初始化
onMounted(() => {
  // 初始化pinia
  userStore.clearUserData()

  // 获取初始设备状态
  isMobile.value = deviceDetector.getCurrentStatus().isMobile
  
  // 添加设备状态变化监听
  deviceDetector.addCallback(handleDeviceChange)
  
  // 初始化验证码
  refreshCaptchaCode()
})

// 组件销毁前清理
onBeforeUnmount(() => {
  // 移除设备状态变化监听
  deviceDetector.removeCallback(handleDeviceChange)
})
</script>

<style scoped>
.login-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
  padding: 20px;
}

.login-wrapper {
  position: relative;
  z-index: 10;
  display: flex;
  width: 100%;
  max-width: 900px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.login-intro {
  flex: 1;
  background: linear-gradient(135deg, #434343 0%, #000000 100%);
  color: white;
  padding: 50px 30px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  transition: all 0.3s ease;
}

.intro-content h1 {
  font-size: 28px;
  margin-bottom: 20px;
  font-weight: 600;
}

.intro-content p {
  font-size: 16px;
  margin-bottom: 30px;
  opacity: 0.9;
}

.features {
  margin-top: 30px;
}

.feature-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
}

.feature-item i {
  color: #409EFF;
  margin-right: 10px;
  font-size: 18px;
}

.login-box {
  flex: 1;
  padding: 40px 30px;
  min-width: 350px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  font-size: 14px;
  color: #666;
}

.login-form {
  margin-bottom: 20px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.forgot-password {
  font-size: 13px;
  color: #409EFF;
  text-decoration: none;
}

.forgot-password:hover {
  color: #66b1ff;
}

.login-button {
  margin-top: 10px;
  background-color: #409EFF;
  border-color: #409EFF;
}

.login-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.login-footer {
  text-align: center;
  font-size: 13px;
  color: #666;
}

.register-link {
  color: #409EFF;
  text-decoration: none;
}

.register-link:hover {
  color: #66b1ff;
}

.other-login {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.other-icon {
  margin: 0 10px;
  font-size: 20px;
  color: #666;
  cursor: pointer;
}

.other-icon:hover {
  color: #409EFF;
}

.background-decoration .circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.circle-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  right: -100px;
}

.circle-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  left: -80px;
}

.circle-3 {
  width: 150px;
  height: 150px;
  top: 200px;
  left: 100px;
}

.el-form-item {
  margin-bottom: 20px;
}

/* 验证码样式 */
.captcha-form-item {
  margin-bottom: 15px;
}

.captcha-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.loading-captcha {
  font-size: 12px;
  color: #999;
}

/* 修复输入框样式问题 */
:deep(.el-input__inner) {
  border-radius: 8px;
  padding-left: 40px;
  height: 40px;
  line-height: 40px;
}

:deep(.el-input__prefix) {
  left: 12px;
}

:deep(.el-input--large .el-input__inner) {
  height: 40px;
  line-height: 40px;
}

/* 修复按钮样式问题 */
:deep(.el-button--primary) {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
  color: white;
}

:deep(.el-button--primary:active) {
  background-color: #3a8ee6;
  border-color: #3a8ee6;
}

:deep(.el-button) {
  border-radius: 8px;
  font-size: 16px;
  padding: 12px 20px;
}

/* 平板设备响应式 */
@media (max-width: 992px) {
  .login-wrapper {
    max-width: 700px;
  }
  
  .login-intro {
    padding: 30px 20px;
  }
  
  .intro-content h1 {
    font-size: 24px;
  }
  
  .login-box {
    padding: 30px 25px;
  }
}

/* 手机设备响应式 */
@media (max-width: 768px) {
  .login-container {
    padding: 10px;
  }
  
  .login-wrapper {
    flex-direction: column;
    max-width: 100%;
    border-radius: 10px;
  }
  
  .login-intro {
    padding: 30px 20px;
    text-align: center;
  }
  
  .login-intro.hidden {
    display: none;
  }
  
  .login-box {
    width: 100%;
    min-width: auto;
    padding: 30px 20px;
  }
  
  .title {
    font-size: 24px;
  }
  
  .form-options {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .forgot-password {
    margin-top: 10px;
  }
  
  .other-login {
    flex-direction: column;
  }
  
  .other-login span {
    margin-bottom: 10px;
  }
  
  /* 移动端验证码布局 */
  .captcha-wrapper {
    flex-direction: column;
    align-items: stretch;
  }
  
  .captcha-image {
    width: 100%;
    margin-top: 10px;
  }
}

/* 小屏幕手机 */
@media (max-width: 480px) {
  .login-container {
    padding: 5px;
  }
  
  .login-box {
    padding: 20px 15px;
  }
  
  .title {
    font-size: 22px;
  }
  
  .other-icon {
    margin: 0 5px;
    font-size: 18px;
  }
  
  .circle-1, .circle-2, .circle-3 {
    display: none;
  }
  
  :deep(.el-button) {
    padding: 10px 15px;
    font-size: 14px;
  }
}
</style>